/**
 * 是否启用pdf，true启用,false不启用
 */
var startPdfPreview = false;

/**
 * 创建DSYWidget管理器
 */
if (!window.DSYWidget) {
    window.DSYWidget = {
        Manager: {
            grid: {}
        }
    };
    window.DSYWidget = DSYWidget;
} else if (!window.DSYWidget.Manager) {
    window.DSYWidget.Manager = {
        grid: {}
    };
} else if (!window.DSYWidget.Manager.grid) {
    window.DSYWidget.Manager.grid = {};
}

var webuploader_chunk_size = 512 * 1024;
var webuploader_file_info = {}; // 附件信息
var webuploader_file_status = false; // 附件上传状态
var is_install_flash = true; // 在IE下是否安装了flash插件
var is_must_upload = false; // 判断是否是必传附件
var browserInfo = getBrowserInfo(); //判断当前浏览器版本
var IE8Del = false; //做IE8兼容处理
if(browserInfo["browser"] == "IE" && (browserInfo["version"] == "8.0" || browserInfo["version"] == "9.0")){
	IE8Del = true;
}
var webuploader_file_speed = {}; //存储上传速度信息
function UploadPanel() {
};

UploadPanel.createGrid = function(config) {
	if(!config.gridConfig.itemId){
		config.gridConfig.itemId = 'webuploader_ext_dsygrid';
	}
	return createWebUploader(config);
};

/**
 * 下载flash插件
 * @param fileName
 */
function uploadFlashTool(fileName){
	window.location.href="/report/sys-manage/downLoadTool?url="+encodeURI(encodeURI(fileName));
}

/**
 * 新版图片预览弹出框
 */
function imageAfterLoad(self, fileId) {
	new Viewer(self, {
	   url: 'data-original',
	   navbar: false,
	   zIndex: 20000,
	   container: document.body,
	   title: true,
	   toolbar: {
           zoomIn: 1,
           zoomOut: 1,
           oneToOne: 1,
           reset: 1,
           prev: 0,
           play: 0,
           next: 0,
           rotateLeft: 1,
           rotateRight: 1,
           flipHorizontal: 1,
           flipVertical: 1
       },
	   viewed: function(self) {
		    var viewers = window.top.document.getElementsByClassName("viewer-toolbar");
		    for(var i = 0; i < viewers.length; i++) {
		    	var viewer = viewers[i].firstChild;
				if(viewer.getElementsByClassName("viewer-zoom-down").length === 0 && !$(viewers[i]).is(':hidden')) {
					var li = document.createElement("li");
					li.setAttribute("onclick", "UploadPanel.downloadFile('" + fileId + "')");
					li.setAttribute("class", "viewer-zoom-down");
					li.setAttribute("title", "下载");
					viewer.appendChild(li);
				}
		    }
	   }
	});
}

/**
 * 创建图片预览弹出框
 */
function imageClick(file_id) {
    top.Ext.create('Ext.window.Window', {
        title: '图片预览',
        maximizable: true,
        modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
        width: top.document.body.clientWidth * 0.75,
        height: top.document.body.clientHeight * 0.75,
        scrollable: true,
        items: {
            xtype: 'box', //或者xtype: 'component',
            layout: 'hbox',
            autoEl: {
                tag: 'img',    //指定为img标签
                src: '/report/third-api/uploadFile/previewReadyImage?fileId=' + file_id  //指定url路径
            }
        }
    }).show();
}
/**
 * 自定义js数组方法，数组中是否包含某元素
 * @param needle
 * @returns {Boolean}
 */
function arrayContainsString(array, needle){
	for (var i in array) {
		if (array[i] == needle.toLowerCase()) return true;
	}
	return false;
}

/**
 * 判断选择是否必传
 */
function changeSelected(select){
	is_must_upload = select;
}

/**
 * 判断map是否相等
 * @param sourceMap
 * @param dirMap
 * @returns {Boolean}
 */
function equalsMap(dirMap, sourceMap){
	for(var value in sourceMap){
		if(value != 'chunk' && value != 'chunks' && value != 'file_guid'){
			if(sourceMap[value] != dirMap[value]){
				return false;
			}			
		}
	}
	return true;
}

function onmouseoverdivIE(self, select) {
	if (!is_install_flash) {
		if (!Ext.ComponentQuery.query('window#ie-flash-tip-info')[0]) {
			Ext.create('Ext.window.Window',{
				title : '提示信息',
				itemId : 'ie-flash-tip-info',
				width : 300,
				height : 140,
				buttonAlign : 'center',
				buttons : [ {
					text : '确定',
					handler : function(btn) {
						btn.up('window').close();
					}
				} ],
				items : [ {
					xtype : 'tbtext',
					margin : '10 10 10 10',
					html : '请先安装flash插件！点击此处下载'
							+ '<a href="/report/tool/install_flash_player_ax23.0.exe">flash插件</a></br>（安装成功后请重新登录系统再操作）'
				} ]
			}).show();
		} else {
			Ext.ComponentQuery.query('window#ie-flash-tip-info')[0].show();
		}
	}
	is_must_upload = select;
	$(self).click();
}

function onmouseleavedivIE(){
	is_must_upload = true;
}

/**
 * 预览pdf文件
 */
function pdfPreviewFile(fileId, form){
    Ext.Ajax.request({
        method: 'GET',
        url: "/report/third-api/uploadFile/queryFileIsExist",
        params: {
            fileId: fileId
        },
        success: function (res) {
            var data = Ext.util.JSON.decode(res.responseText);
            if (data) {
                form = encodeURI(form);
                var href = "/report/third/pdf/web/viewerPdf.html?fileId=" + fileId + "&fileName=" + form;
                window.open(href);
            } else {
                Ext.Msg.alert('提示', "您要预览的资源不存在！" + data.message);
            }
        },
        failure: function (form, action) {
            Ext.Msg.alert('提示', "您要预览的资源不存在！" + action.result ? action.result.message : '无返回响应');
        }
    });
	// var tempWindow = window.open('/report/page/frame/loading.jsp');
	// $.post("/report/sys-manage/previewPdfFilePath",{
	// 	file_id: fileId,
	// 	form: form
	// }, function(data){
	// 	tempWindow.location = data.localPath;
	// }, 'json');
}

/**
 * 创建文件上传封装对象
 */
function createWebUploader(createConfig) {
    /**
     * 上传控件表头
     * @type {*[]}
     */
    this.headerJson = [
        {
            text: "操作", menuDisabled: true, sortable: false,
            renderer: function (value, cell, record, rowIndex, colIndex, store, view) {
            	var select = false;
            	if(record.get("RULE_ID")) {
            		select = true;
            	}
            	//上传提示信息
                var tipText = '小于' + record.data.MAXLIMIT / 1024 + 'MB';
                var tip = record.data.FILE_SUFFIX + tipText;
                var uploadbtn;
                if(IE8Del){
                	uploadbtn = '<div title="' + tip + '" class="uploadpanel-btn uploadpanel-btn-upload ' + createConfig.gridConfig.itemId + '-upload ' + createConfig.gridConfig.itemId +'-btn" onmouseenter="onmouseoverdivIE(this,' + select + ')"></div>';
                }else{
                	uploadbtn = '<div title="' + tip + '" class="uploadpanel-btn uploadpanel-btn-upload ' + createConfig.gridConfig.itemId + '-upload ' + createConfig.gridConfig.itemId +'-btn" onclick="changeSelected(' + select + ')"></div>';
                }
                var downloadbtn = '<div title="下载" class="uploadpanel-btn uploadpanel-btn-download" onclick="UploadPanel.downloadFile(\'' + record.get("FILE_ID") + '\')"></div>';
                var deletebtn = '<div title="删除" class="uploadpanel-btn uploadpanel-btn-delete" onclick="UploadPanel.deleteFile(\'' + record.get("FILE_ID") + '\',\'' + record.get("RULE_ID") + '\',\'' + record.get("FILE_NAME") + '\',\'' + createConfig.gridConfig.itemId + '\',\'' + rowIndex + '\')"></div>';
                var preview = ''; // 预览按钮
                //如果文件存在，隐藏上传按钮
                var fileId = record.data.FILE_ID;
                var fileName = record.data.FILE_NAME;
                if (typeof fileId != 'undefined' && fileId != null && fileId != '') {
                    uploadbtn = ''; // 存在隐藏上传按钮
                    var form = record.data.FILE_NAME.split(".")[record.data.FILE_NAME.split(".").length - 1].toLowerCase();
                    if((form == 'pdf' || form == 'docx' || form == "doc") && startPdfPreview){
                    	preview = '<div title="预览" class="uploadpanel-btn uploadpanel-btn-preview" onclick="pdfPreviewFile(\'' + fileId + '\',\'' + fileName + '\')"></div>';
                    }
                }else{ //根据文件id是否存在，隐藏下载按钮
                	downloadbtn = ''; // 不存在，隐藏下载按钮
                }
                if(createConfig.editable){
                	return '<div class="uploadpanel-btsn">' + uploadbtn + downloadbtn + deletebtn + preview + '</div>';
                }else{
                	return '<div class="uploadpanel-btsn">' + downloadbtn + preview + '</div>';
                }
            }
        },
        {text: "业务类型", dataIndex: "BUSI_TYPE", type: "string", hidden: true},
        {text: "业务规则", dataIndex: "BUSI_PROPERTY", type: "string", hidden: true},
        {text: "规则id", dataIndex: "RULE_ID", type: "string", hidden: true},
        {
            text: "上传文件名称", dataIndex: "FILE_NAME", width: 330, type: "string", cellWrap: true,
            renderer: function (data, cell, record) {
                //给文件添加超链接
                var file_id = record.get('FILE_ID');
                //当为必选项，并且file_id为空的时候，行背景色为淡黄色
                var star = '';
                if (record.get('NULLABLE') == 'N' && (createConfig.isMustUpload != false)) {
                    star = '<span class="required">✶</span>';
                    if (typeof(file_id) == "undefined" || file_id == null || file_id == '' || file_id == 'null' || file_id == '0') {
                        star = '<span class="required">✶必录附件</span>';
                    }
                }
                var form = data.split(".")[data.split(".").length - 1];
                if(!!form) {
                	form = form.toLowerCase();
                	if(form == "dps" || form == "dpt" || form == "odp" || form == "otp") {
                    	form = "pdf";
                    }else if(form == "wps" || form == "wpt" || form == "odt" || form == "ott") {
                    	form = "docx";
                    }else if(form == "et" || form == "ett" || form == "ods" || form == "ots") {
                    	form = "xlsx";
                    }
                }
                var image = '';
                if (form != null && form != "") {
                    image = '<image src="/report/image/file/' + form + '.png">&nbsp';
                }
                if (form == "png" || form == "jpg" || form == "jpeg") {
                	if (browserInfo["browser"] === "IE" && browserInfo["version"] === "8.0") {
						image = "<image style='width:64px;height:64px;cursor:pointer;' onclick='imageClick(\"" + file_id + "\")' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "'/>";
					}else {
						image = "<image style='width:64px;height:64px;cursor:pointer;' data-original='/report/third-api/uploadFile/previewReadyImage?fileId=" + file_id +
                    	"' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "' onload='imageAfterLoad(this, \"" + file_id + "\")' alt='" + data + "' title='" + data + "'/>";
					}
                }
                return star + image + '<a href="javascript:void(0);" style="color:#3329ff;" onclick="UploadPanel.downloadFile(\'' + file_id + '\')">' + data + '</a>';
            }
        },
        {
            text: "附件描述", dataIndex: "FILE_DESC", width: 300, type: "string", cellWrap: true,
            renderer: function (data, cell, record) {
                //当附件id存在，并且业务规则不存在时，附件描述为：自行提交的附件
                var fild_id = record.get("FILE_ID");
                var busi_property = record.get('BUSI_PROPERTY');
                var file_name = record.get('FILE_NAME');
                if ((busi_property == null || busi_property == '' || busi_property == 'null') &&
                    (fild_id != null && fild_id != '' && fild_id != 'null' && fild_id != '0')) {
                    return data ? data : file_name;
                }
                return data;
            }
        },
        {
            text: "文件大小", dataIndex: "FILE_SIZE", width: 125, type: "string",
            renderer: function (data, cell, record) {
                if (isNaN(parseFloat(data))) {
                    return data;
                } else if (parseFloat(data) < (1024 * 1024)) {
                    return (parseFloat(data) / 1024).toFixed(2) + 'KB';
                }
                return (parseFloat(data) / (1024 * 1024)).toFixed(2) + 'MB';
            }
        },
        {
            text: "文件类型限制", dataIndex: "FILE_SUFFIX", width: 125, type: "string", hidden: true, cellWrap: true
        },
        {
            text: "文件大小限制", dataIndex: "LIMIT_SIZE", width: 125, type: "string", hidden: true,
            renderer: function (data, cell, record, rowIndex, colIndex, store, view) {
                var text = '';
                if (!record.get('RULE_ID')) {
                    var uploadConfig = UploadPanel.getConfig(view.grid.itemId).config;
                    record.data.MINLIMIT = 0;
                    record.data.MAXLIMIT = uploadConfig.file_size;
                    record.data.LIMIT_SIZE = '0-' + uploadConfig.file_size + 'KB';
                }
                if (record.data.MINLIMIT && record.data.MINLIMIT > 1) {
                    text = '大于' + record.data.MINLIMIT / 1024 + 'MB';
                }
                return text + '小于' + record.data.MAXLIMIT / 1024 + 'MB';
            }
        },
        {text: "上传状态", dataIndex: "STATUS", type: "string", hidden: true},
        {text: "文件ID", dataIndex: "FILE_ID", type: "string", hidden: true},
        {text: "文件最小值", dataIndex: "MINLIMIT", type: "int", hidden: true},
        {text: "文件最大值", dataIndex: "MAXLIMIT", type: "int", hidden: true},
        {text: "是否限制文件的类型", dataIndex: "IS_LIMITTYPE", type: "string", hidden: true},
        {text: "是否限制文件的大小", dataIndex: "IS_LIMITSIZE", type: "string", hidden: true},
        {text: "是否必须上传", dataIndex: "NULLABLE", type: "string", hidden: true}
    ];
    this.headerJson_FREE = [
        {
            xtype: 'rownumberer',
            width: 20
        },
        {
            text: "操作", menuDisabled: true, sortable: false,
            renderer: function (value, cell, record, rowIndex, colIndex, store, view) {
            	//上传提示信息
                var tipText = '小于' + record.data.MAXLIMIT / 1024 + 'MB';
                var tip = record.data.FILE_SUFFIX + tipText;
                var uploadbtn;
                if(IE8Del){
                	uploadbtn = '<div title="' + tip + '" class="uploadpanel-btn uploadpanel-btn-upload ' + createConfig.gridConfig.itemId + '-upload ' + createConfig.gridConfig.itemId +'-btn" onmouseenter="onmouseoverdivIE(this)"></div>';
                }else{
                	uploadbtn = '<div title="' + tip + '" class="uploadpanel-btn uploadpanel-btn-upload ' + createConfig.gridConfig.itemId + '-upload ' + createConfig.gridConfig.itemId +'-btn" onclick="changeSelected()"></div>';
                }
                var downloadbtn = '<div title="下载" class="uploadpanel-btn uploadpanel-btn-download" onclick="UploadPanel.downloadFile(\'' + record.get("FILE_ID") + '\')"></div>';
                var deletebtn = '<div title="删除" class="uploadpanel-btn uploadpanel-btn-delete" onclick="UploadPanel.deleteFile(\'' + record.get("FILE_ID") + '\',\'' + record.get("RULE_ID") + '\',\'' + record.get("FILE_NAME") + '\',\'' + createConfig.gridConfig.itemId + '\',\'' + rowIndex + '\')"></div>';
                var preview = ''; // 预览按钮
                //如果文件存在，隐藏上传按钮
                var fileId = record.data.FILE_ID;
                var fileName = record.data.FILE_NAME;
                if (typeof fileId != 'undefined' && fileId != null && fileId != '') {
                    uploadbtn = ''; // 存在隐藏上传按钮
                    var form = record.data.FILE_NAME.split(".")[record.data.FILE_NAME.split(".").length - 1].toLowerCase();
                    if((form == 'pdf' || form == 'docx' || form == "doc") && startPdfPreview){
                    	preview = '<div title="预览" class="uploadpanel-btn uploadpanel-btn-preview" onclick="pdfPreviewFile(\'' + fileId + '\',\'' + fileName + '\')"></div>';
                    }
                }else{ //根据文件id是否存在，隐藏下载按钮
                	downloadbtn = ''; // 不存在，隐藏下载按钮
                }
                if(createConfig.editable){
                	return '<div class="uploadpanel-btsn">' + uploadbtn + downloadbtn + deletebtn + preview + '</div>';
                }else{
                	return '<div class="uploadpanel-btsn">' + downloadbtn + preview + '</div>';
                }
            }
        },
        {
            text: "上传文件名称", dataIndex: "FILE_NAME", width: 330, type: "string", cellWrap: true,
            renderer: function (data, cell, record) {
                //给文件添加超链接
                var file_id = record.get('FILE_ID');
                //当为必选项，并且file_id为空的时候，行背景色为淡黄色
                var star = '';
                if (record.get('NULLABLE') == 'N' && (createConfig.isMustUpload != false)) {
                    star = '<span class="required">✶</span>';
                    if (typeof(file_id) == "undefined" || file_id == null || file_id == '' || file_id == 'null' || file_id == '0') {
                        star = '<span class="required">✶必录附件</span>';
                    }
                }
                var form = data.split(".")[data.split(".").length - 1];
                if(!!form) {
                	form = form.toLowerCase();
                	if(form == "dps" || form == "dpt" || form == "odp" || form == "otp") {
                    	form = "pdf";
                    }else if(form == "wps" || form == "wpt" || form == "odt" || form == "ott") {
                    	form = "docx";
                    }else if(form == "et" || form == "ett" || form == "ods" || "ots") {
                    	form = "xlsx";
                    }
                }
                var image = '';
                if (form != null && form != "") {
                    image = '<image src="/report/image/file/' + form + '.png">&nbsp';
                }
                if (form == "png" || form == "jpg" || form == "jpeg") {
                	if (browserInfo["browser"] === "IE" && browserInfo["version"] === "8.0") {
						image = "<image style='width:64px;height:64px;cursor:pointer;' onclick='imageClick(\"" + file_id + "\")' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "'/>";
					}else {
						image = "<image style='width:64px;height:64px;cursor:pointer;' data-original='/report/third-api/uploadFile/previewReadyImage?fileId=" + file_id +
                    	"' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "' onload='imageAfterLoad(this, \"" + file_id + "\")' alt='" + data + "' title='" + data + "'/>";
					}
                }
                return star + image + '<a href="javascript:void(0);" style="color:#3329ff;" onclick="UploadPanel.downloadFile(\'' + file_id + '\')">' + data + '</a>';
            }
        },
        {
            text: "文件大小", dataIndex: "FILE_SIZE", width: 125, type: "string",
            renderer: function (data, cell, record) {
                if (isNaN(parseFloat(data))) {
                    return data;
                } else if (parseFloat(data) < (1024 * 1024)) {
                    return (parseFloat(data) / 1024).toFixed(2) + 'KB';
                }
                return (parseFloat(data) / (1024 * 1024)).toFixed(2) + 'MB';
            }
        },
        {
            text: "文件类型限制", dataIndex: "FILE_SUFFIX", width: 125, type: "string", cellWrap: true, hidden: true
        },
        {
            text: "文件大小限制", dataIndex: "LIMIT_SIZE", width: 125, type: "string", hidden: true,
            renderer: function (data, cell, record, rowIndex, colIndex, store, view) {
                var text = '';
                if (!record.get('RULE_ID')) {
                    var uploadConfig = UploadPanel.getConfig(view.grid.itemId).config;
                    record.data.MINLIMIT = 0;
                    record.data.MAXLIMIT = uploadConfig.file_size;
                    record.data.LIMIT_SIZE = '0-' + uploadConfig.file_size + 'KB';
                }
                if (record.data.MINLIMIT && record.data.MINLIMIT > 1) {
                    text = '大于' + record.data.MINLIMIT / 1024 + 'MB';
                }
                return text + '小于' + record.data.MAXLIMIT / 1024 + 'MB';
            }
        },
        {text: "上传状态", dataIndex: "STATUS", type: "string", hidden: true}
    ];
    this.config = {
        file_type: null,//系统变量文件类型
        file_size: null,//系统变量文件大小
        file_store_mode: null,//系统变量文件储存方式
        busiType: null,//busi_type业务类型
        busiId: null,//busi_id业务ID
        busiProperty: '%',//业务规则
        editable: true,//是否可对附件进行操作
        addfileable: true,//是否可对附件进行新增行操作
        headerType: '',//表头类型：默认为headerJson,FREE：为headerJson_FREE，DIY：为用户自定义
        grid: null,//表格
        gridConfig: {//表格配置
            itemId: createConfig.gridConfig.itemId,
            headerConfig: {
                headerJson: createConfig.headerType == 'FREE' ? this.headerJson_FREE : this.headerJson,
                columnAutoWidth: false
            },
            dockedItems: addUploadBtn(createConfig),
            listeners: {
            	viewready: function(self){
            		$.ajax({
                        type: "POST",
                        url: '/report/third-api/api/sys-data/paramValueAll',
                        async: false, //设为false就是同步请求
                        cache: false,
                        success: function (jsonData) {
                            // var data = JSON.parse(jsonData.data);
                            var fileConfig = {};
                            fileConfig["file_type"] = jsonData['DEBT_FILE_TYPE'];
                            fileConfig["file_size"] = jsonData['DEBT_FILE_SIZE'];
                            fileConfig["file_store_mode"] = jsonData['FILE_STORE_MODE'];
                            try{
                        		uploaders(createConfig, fileConfig, self);
                            }catch(e){
                            	is_install_flash = false; // 没有安装flash插件
                            }
                        }
                    });
            	}
            },
            margin: '0 0 25 0',
            height: '100%',
            border: false,
            dataUrl: '/report/third-api/uploadFile/list',
            pageConfig: {
                enablePage: false
            },
            plugins: [
              {
                  ptype: 'cellediting',
                  clicksToEdit: 1,
                  pluginId: 'fileGrid_cellediting',
                  clicksToMoveEditor: 1,
                  listeners: {
                	  beforeedit: function (editor, context) {
                		  if(!createConfig.editable) {
                			  return false;
                		  }
                		  if(!context.record.data.FILE_ID) {
                			  Ext.toast({
                                  html: "请先上传附件！",
                                  closable: false,
                                  align: 't',
                                  slideInDuration: 400,
                                  minWidth: 400
                              });
                			  return false;
                		  }
                      }
                  }
              }
            ]
        }
    };
    //设置表格参数
    this.config.gridConfig.params = $.extend({
        busiType: createConfig.busiType,
        ruleIds: !!createConfig.ruleIds ? createConfig.ruleIds.join(",") : '',
        isFilter: createConfig.isFilter,
        busiId: createConfig.busiId,
        busiProperty: createConfig.busiProperty?createConfig.busiProperty:'%',
        editable: createConfig.editable,
        filterParam: createConfig.filterParam
    }, createConfig.gridConfig.params);
    this.config.gridConfig = $.extend(this.config.gridConfig,createConfig.gridConfig);
    //创建表格
  //判断是否增加表格扩展字段
    if(!!createConfig.addHeaders) {
    	var addFields = "";
    	var saveFields = [];
    	var fieldList = "BUSI_PROPERTY_DESC,FILE_NAME FILE_NAME,FILE_SIZE FILE_SIZE,FILE_PATH FILE_PATH,UPLOAD_USER,UPLOAD_TIME,FILE_ID FILE_ID,AD_CODE,AD_NAME,AG_CODE,AG_NAME";
    	for(var i = 0; i < createConfig.addHeaders.length; i++) {
    		if(fieldList.indexOf(createConfig.addHeaders[i].dataIndex) == -1) {
    			addFields += "B." + createConfig.addHeaders[i].dataIndex + ",";
    		}
    		saveFields.push(createConfig.addHeaders[i].dataIndex);
			if(!!createConfig.addHeaders[i].index) {
				this.config.gridConfig.headerConfig.headerJson.splice(createConfig.addHeaders[i].index, 0, createConfig.addHeaders[i]);
			}else {
				this.config.gridConfig.headerConfig.headerJson.push(createConfig.addHeaders[i]);
			}
    	}
    	this.config.gridConfig.params["addFields"] = addFields;
    	this.config.gridConfig.params["saveFields"] = saveFields;
    }
    var grid = DSYGrid.createGrid(this.config.gridConfig);
    return grid;
}
var file_guid = null;
//var uploader = null;
/**
 * 创建上传组件
 * @param config
 * @param fileConfig
 */
function uploaders(config, fileConfig, self){
	var fileMd5 = null; // 前天记录附件唯一标识
	//var file_guid = null; // 后台记录唯一标识号
	webuploader_file_info = { // 初始化附件信息
		"ruleId": config.ruleId,
		"busiId": config.busiId,
		"busiType": config.busiType
	};
	var uploader = WebUploader.create({
		formData: webuploader_file_info,
		auto: true, //是否自动上传
	    swf: '/report/third/webuploader-0.1.5/Uploader.swf', // swf文件路径
	    runtimeOrder: 'html5,flash',  // 优先使用html5上传
	    server: '/report/third-api/uploadFile/file', // 文件接收服务端
	    chunked: false,  //是否分片
	    duplicate: true, // 是否允许重复
	    prepareNextFile: true, // 上传本分片时预处理下一分片
	    chunkRetry: 2, // 如果某个分片由于网络问题出错，允许自动重传多少次
	    chunkSize: webuploader_chunk_size,   //每片5M
	    sendAsBinary: false,//是否已二进制流的方式上传
	    threads: 1,//上传并发数。允许同时最大上传进程数
	    //fileNumLimit: 100, //上传文件个数限制
      	//fileSingleSizeLimit: fileConfig.file_size * 1024,//单个文件大小限制  100M
	    // 只允许选择图片文件
        /*accept: {
            title: '类型限制',
            extensions: file_type
            //mimeTypes: 'image/*',
        },*/
	    pick: {
	    	id: '.' + config.gridConfig.itemId + '-btn',
	    	multiple: false //设置是否允许多文件同时上传
	    },
	    //fileVal:"upload", //重要参数:跟后台文件组件的对接参数，后台文件组件叫做upload,默认file
	    resize: false // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
	});
	$("#ctlBtn").on("click", function() {
	    uploader.upload();
	});
	uploader.on( 'fileQueued', function( file ) {
		if(file.name.length > 100){
			webuploader_file_status = false;
			if(!!Ext.ComponentQuery.query('window#progress_window')[0]){
				Ext.ComponentQuery.query('window#progress_window')[0].close();						
			}
			Ext.MessageBox.alert("提示", "上传失败，文件名称长度超过限制！");
			uploader.removeFile(file);
			return;
		}
		var fileExt = file.ext.toLowerCase();
		if(fileExt == 'png' || fileExt == 'jpg' || fileExt == 'jpeg'){
			uploader.makeThumb( file, function( error, ret ) {
				if (error) {
					webuploader_file_status = false;
					if(!!Ext.ComponentQuery.query('window#progress_window')[0]){
						Ext.ComponentQuery.query('window#progress_window')[0].close();						
					}
					Ext.MessageBox.alert("提示", "上传失败，图片文件已损坏！");
					uploader.removeFile(file);
					return;
				}
			});
		}
		webuploader_file_speed = {};
		webuploader_file_speed["upload_file_start_size"] = getWebuploaderDate();
		webuploader_file_info ={
			"ruleId": config.ruleId,
			"busiId": config.busiId,
			"busiType": config.busiType
		};
		var mustUpload = DSYGrid.getGrid(config.gridConfig.itemId).getCurrentRecord();
		uploader.options.formData.ruleId = '';
		if(is_must_upload && mustUpload && mustUpload.data.RULE_ID && mustUpload.data.FILE_ID == ''){
			uploader.options.formData.ruleId = mustUpload.data.RULE_ID;
			if(mustUpload.data.IS_LIMITTYPE == 1){
				var file_types = mustUpload.data.FILE_SUFFIX.replace(/\./g, '').split("/");
				if(!arrayContainsString(file_types, fileExt)){ //验证附件类型
					Ext.Msg.alert('提示', '文件类型错误,请选择文件' + mustUpload.data.FILE_SUFFIX);
					uploader.removeFile(file, true);
					return true;
				}
			}
			if(mustUpload.data.IS_LIMITSIZE == 1){
				var limit_size = mustUpload.data.LIMIT_SIZE.replace(/\KB/g,'').split('-');
				if(file.size > limit_size[1] * 1024) { //验证附件大小
					Ext.MessageBox.alert('提示', '文件太大，请选择小于' + limit_size[1] + 'KB的文件！');
					uploader.removeFile(file, true);
					return true;
				}
				if(file.size < limit_size[0] * 1024) { //验证附件大小
					Ext.MessageBox.alert('提示', '文件太小，请选择大于' + limit_size[0] + 'KB的文件！');
					uploader.removeFile(file, true);
					return true;
				}
			}
			is_must_upload = false;
		}else{
			var file_types = fileConfig['file_type'].replace(/\./g, '').split("/");
			if(!arrayContainsString(file_types, fileExt)){ //验证附件类型
				Ext.Msg.alert('提示', '文件类型错误,请选择文件' + fileConfig['file_type']);
				uploader.removeFile(file, true);
				return true;
			}
			if(file.size > fileConfig.file_size * 1024) { //验证附件大小
				Ext.MessageBox.alert('提示', '文件太大，请选择小于' + fileConfig.file_size + 'KB的文件！');
				uploader.removeFile(file, true);
				return true;
			}
		}
		Ext.create('Ext.window.Window',{
			itemId: 'progress_window',
	        title: '上传进度',
	        modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
	        width: 600,
	        height: 35,
	        border: false,
	        draggable: false,
	        closable: false,
	        items: [{
        		  xtype: 'progressbar',
        		  layout: 'fit',
        		  border: false,
        		  width: 600,
        		  height: 40,
        		  id: 'progressbar'
            }],
            listeners: {
            	afterlayout: function(self, eOpts){
            		var header = $(self.el.dom).find("div.x-window-header")[0];
            		var body = $(self.el.dom).find("div.x-window-body")[0];
            		var progress_bar = $(self.el.dom).find("div.x-progress-bar-default")[0];
            		//header.parentNode.removeChild(header);
            		header.style.display = 'none';
            		body.style.top = '0px';
            		body.style.left = '0px';
            		body.style.right = '0px';
            		body.style.botton = '0px';
            		body.style.height = '40px';
            		body.style.width = '600px';
            		body.style.border = '2px solid #7A7A7A';
            		document.getElementById("progressbar").style.background='#B4CDCD url(/report/third/webuploader-0.1.5/progress.png) repeat-x';
            		self.el.dom.style.height = '40px';
            		self.el.dom.style.width = '600px';
            		self.el.dom.style.border = '0px solid #FFFFFF';
            		progress_bar.style.backgroundColor = '#90EE90';//'#5CACEE';
            	}
            }
		}).show();
		file_guid = WebUploader.guid(); //生成唯一标识号
		uploader.options.formData.file_guid = file_guid; //将唯一标识号存储到后台
		if(webuploader_file_status){
			Ext.MessageBox.alert('提示','请等待当前附件上传完成！');
			uploader.removeFile(file, true); //将附件从队列中移除
		}else{
			webuploader_file_status = true;//设置附件正在上传状态
			var progressbar = Ext.ComponentQuery.query("#progressbar")[0];
			progressbar.updateProgress(0, '<div style="margin: 10px auto auto auto">等待上传...</div>');
			//UploadPanel.saveExtraField(config.gridConfig.itemId); // 保存自定义数据
		}
	});
	//文件上传过程中创建进度条实时显示
	uploader.on( 'uploadProgress', function( file, percentage ) {
		var speed_percentage = percentage;
		var progressbar = Ext.ComponentQuery.query("#progressbar")[0];
		percentage = Math.floor(percentage * 10000)/100;
		var end_time = getWebuploaderDate()/1000;
		var speed_size = file.size * speed_percentage;
		if( speed_size != 0 && webuploader_file_speed["start_time"] && 
				webuploader_file_speed["speed_size"]){
			speed = (speed_size - webuploader_file_speed["speed_size"])/(end_time - webuploader_file_speed["start_time"])/1024;
			uploader.options.formData.webuploader_speed = Math.floor(speed * 100) / 100;
			if(speed >= 1000){
				speed = Math.floor(speed/1024 * 100) / 100;
				speed_unit = 'MB/S ';
			} else{
				speed = Math.floor(speed * 100) / 100;
				speed_unit = 'KB/S ';
			}
			progressbar.updateProgress(percentage/100, '<div style="margin: 10px auto auto auto">（' + file.name + ' ' + Math.floor(file.size/1024/1024*100)/100 + 'MB） ' + percentage + '%  ' + speed + speed_unit + '</div>');
			if(percentage == 100){
				webuploader_file_speed["start_time"] = null;
				webuploader_file_speed["speed_size"] = null;
				progressbar.updateProgress(100, '<div style="margin: 10px auto auto auto">上传完成!后台存储中...</div>');
			}
		} else {
			webuploader_file_speed["start_time"] = end_time;
			webuploader_file_speed["speed_size"] = speed_size;
			if(percentage != 100){
				progressbar.updateProgress(0, '<div style="margin: 10px auto auto auto">正在上传...</div>');				
			}
		}
		
	});
	
	uploader.on( 'uploadSuccess', function( file ) {
		var upload_time = getWebuploaderDate() - webuploader_file_speed["upload_file_start_size"];
		$.post("/report/sys-manage/recordUploadFileLog",{
			upload_time: upload_time,
			upload_file_size: file.size/1024,
			upload_file_name: file.name
		},function(){
		},'json');
		var progressbar = Ext.ComponentQuery.query("#progressbar")[0];
		webuploader_file_status = false;//设置附件不在上传状态
		if(!!progressbar){
			progressbar.updateProgress(1, '<div style="margin: 10px auto auto auto">上传成功</div>');			
		}
	});

	uploader.on( 'uploadError', function( file, reason) {
		var progressbar = Ext.ComponentQuery.query("#progressbar")[0];
		webuploader_file_status = false;//设置附件不在上传状态
		progressbar.updateProgress(1, '<div style="margin: 10px auto auto auto">上传出错</div>');
	});

	uploader.on( 'uploadComplete', function( file ) {
		if(Ext.ComponentQuery.query('window#progress_window')[0]){
			try{
				Ext.ComponentQuery.query('window#progress_window')[0].close();
			}catch(e){
				Ext.ComponentQuery.query('window#progress_window')[0].close();
			}
		}
		if(DSYGrid.getGrid(config.gridConfig.itemId)){
			try{
				reloadWebUploaderGrid(config.gridConfig.itemId);
			}catch(e){
				reloadWebUploaderGrid(config.gridConfig.itemId);
			}
		}
	});
	var grid = DSYGrid.getGrid(config.gridConfig.itemId);
	grid.addListener("beforedestroy",function(self){
		/*uploader.destroy();*/
	});
	grid.getStore().addListener("remove",function(self){
		uploader.addButton({
			id: '.' + config.gridConfig.itemId + '-upload',
			multiple: false //设置是否允许多文件同时上传
		});
	});
	grid.down("button").addListener('click',function(btn){
		var file_size = UploadPanel.getConfig(btn.up('grid').itemId).config.file_size;
        var file_type = UploadPanel.getConfig(btn.up('grid').itemId).config.file_type;
        btn.up('grid').insertData(null, {
            FILE_ID: null,
            FILE_NAME: null,
            LIMIT_SIZE: '0-' + file_size + 'KB',
            MINLIMIT: 0,
            MAXLIMIT: file_size,
            FILE_SUFFIX: file_type
        });
		uploader.addButton({
			id: '.' + config.gridConfig.itemId + '-upload',
			multiple: false //设置是否允许多文件同时上传
		});
	});
	grid.getStore().addListener("load",function(self){
		uploader.addButton({
			id: '.' + config.gridConfig.itemId + '-upload',
			multiple: false //设置是否允许多文件同时上传
		});
	});
	
}

/**
 * 刷新表格的方法
 * @param uploader
 * @param gridId
 */
function reloadWebUploaderGrid(gridId){
	DSYGrid.getGrid(gridId).getStore().load();
}

/**
 * 保存额外字段
 * @param config
 */
/*UploadPanel.saveExtraField = function(itemId, isReload) {
	var grid = DSYGrid.getGrid(itemId);
	var store = grid.getStore();
	var fieldList = store.getProxy().extraParams["saveFields"];
	if(!fieldList) {
		return;
	}
	var items = grid.getStore().data.items;
	var params = [];
	var fields = fieldList;
	for(var i = 0; i < items.length; i++) {
		var param = {};
		for(var j = 0; j < fieldList.length; j++) {
			if(!!fieldList[j]) {
				var field = fieldList[j];
				param[field] = items[i].data[field];
			}
		}
		param["FILE_ID"] = items[i].data["FILE_ID"];
		params.push(param);
	}
	if(fields.indexOf("FILE_ID") == -1) {
		fields.push("FILE_ID");
	}
	$.ajax({
        type: "post",
        url:"/report/sys-manage/saveExtraField",
        data:{
        	params: Ext.util.JSON.encode(params),
    		fields: fields.join(",")
        },
        dataType:"json",
        async:false,// 同步
        success: function(data) {
        	if(!data.SUCCESS) {
    			Ext.MessageBox.alert("提示", "附件信息保存失败！");
    		}else if(!!isReload){
    			store.reload();
    		}
        }
	});
}*/

/**
 * 删除附件
 * @param fileId 附件id
 * @param rule_id 规则id
 * @param file_name 附件名称
 * @param itemId 表格itemId
 * @param itemId 当前行
 * @return {boolean}
 */
UploadPanel.deleteFile = function (fileId, rule_id, file_name, itemId, rowIndex) {
    if (typeof file_name == 'undefined' || file_name == null || file_name == '' || file_name.toLowerCase() == 'undefined' || file_name.toLowerCase() == 'null') {
        file_name = '';
    }
    if (typeof fileId == 'undefined' || fileId == null || fileId == '' || fileId.toLowerCase() == 'undefined' || fileId.toLowerCase() == 'null') {
        if (typeof rule_id == 'undefined' || rule_id == null || rule_id == '' || rule_id.toLowerCase() == 'undefined' || rule_id.toLowerCase() == 'null') {
            //无文件、无规则，直接删除行
            DSYGrid.getGrid(itemId).getStore().removeAt(rowIndex);
            return false;
        } else {
            //无文件，有规则，不做删除
            return false;
        }
    }
    Ext.Msg.confirm('提示', '是否删除附件 ' + file_name, function (btn) {
        if (btn == 'yes') {
            //发送请求:删除当前附件
            Ext.Ajax.request({
                method: 'DELETE',
                url: '/report/third-api/uploadFile/deleteFile',
                params: {
                    fileIdArray: Ext.util.JSON.encode([{FILE_ID: fileId}])
                },
                success: function (response) {
                    var responseJson = Ext.JSON.decode(response.responseText);
                    if (responseJson.success) {
                        //提示删除成功
                        Ext.toast({
                            html: '<div style="text-align: center;">删除成功!</div>',
                            closable: false,
                            align: 't',
                            slideInDuration: 400,
                            minWidth: 400
                        });
                    } else {
                        Ext.Msg.alert('提示', '删除失败 ' + responseJson.message);
                    }
                    if (typeof itemId != 'undefined' && itemId != null && itemId != '') {
                    	reloadWebUploaderGrid(itemId);
                    }
                }
            });
        }
    });
};

/**
 * 下载附件
 */
UploadPanel.downloadFile = function (file_id) {
    if (typeof(file_id) != "undefined" && file_id != '' && file_id != 0) {
        //向后台传递变更数据信息
        Ext.Ajax.request({
            method: 'GET',
            url: "/report/third-api/uploadFile/queryFileIsExist",
            params: {
                fileId: file_id
            },
            success: function (form, action) {
                var data = Ext.util.JSON.decode(form.responseText);
                if (!data) {
                    Ext.Msg.alert('提示', "下载失败！" + data.message);
                } else {
                    // window.location.href = '/report/third-api/downloadFile?fileId=' + file_id;
                    downloadPublicFiles('/report/third-api/downloadFile', "GET", {
                        fileId:file_id
                    })
					//Ext.Ajax.request({
					//	method: 'POST',
					//	url: "/report/sys-manage/downloadFile/" + file_id,
					//	params: {
					//		file_id: file_id
					//},
					//success: function (form, action) {
					//
					//	console.log(action);
					//	console.log(form);
					//}});
                }
            },
            failure: function (form, action) {
                Ext.Msg.alert('提示', "下载失败！" + action.result ? action.result.message : '无返回响应');
            }
        });
    } else {
        Ext.Msg.alert('提示', '该附件尚未上传！');
    }
    //阻止超链接
    return false;
};

/**
 * 表格获取方法
 */
UploadPanel.getConfig = function (itemId) {
    return DSYWidget.Manager.grid[itemId];
};

/**
 * 前台校验：必传附件是否全部上传
 */
UploadPanel.validateGrid = function (itemId) {
    if (typeof itemId == 'undefined') {
        itemId = 'UploadGrid';
    }
    var grid = Ext.ComponentQuery.query('grid#' + itemId)[0];
    var flag = true;
    grid.getStore().each(function (record) {
        //当为必选项，并且file_id为空的时候，行背景色为淡黄色
        var fild_id = record.get("FILE_ID");
        if (record.get('NULLABLE') == 'N' && (typeof(fild_id) == "undefined" || fild_id == null || fild_id == '' || fild_id == 'null' || fild_id == '0')) {
            flag = false;
        }
    });
    return flag;
};

/**
 * 后台校验：必传附件是否全部上传
 * @param busiId 业务ID
 * @param busiType 业务类型
 * @param busiProperty 业务规则
 * @return boolean true:通过校验，false：未通过校验
 */
UploadPanel.validateNeed = function (busiId, busiType, busiProperty) {
    var flag = true;
    $.ajax({
            url: '',
            data: {},
            async: false,
            success: function (data) {

            }
        }
    );
    return flag;
};

/**
 * 清除已上传附件
 * @param busi_id 业务Id
 * @param callback 回调函数
 */
UploadPanel.clearFile = function (busi_id, callback) {
    //发送请求:删除当前附件
    Ext.Ajax.request({
        url: '/report/sys-manage/clearFile',
        params: {
            BUSI_ID: busi_id
        },
        success: function (response) {
            var responseJson = Ext.JSON.decode(response.responseText);
            if (Ext.isFunction(callback)) {
                callback(responseJson);
            }
        }
    });
};

WebUploader.Uploader.register({
    "before-send-file":"beforeSendFile",//整个文件上传前
    "before-send":"beforeSend",  //每个分片上传前
    "after-send-file":"afterSendFile"  //分片上传完毕  
},
{
    beforeSendFile:function(file){ //时间点1：所有分块进行上传之前调用此函数
    	var uploaderOpera = this.owner;
        var deferred = WebUploader.Deferred();
        var progressbar = Ext.ComponentQuery.query("#progressbar")[0];
        (new WebUploader.Uploader()).md5File(file).progress(function(percentage){
        	progressbar.updateProgress(0, '<div style="margin: 10px auto auto auto">正在读取文件信息...</div>');
    	}).then(function(val){
    		fileMd5 = val; // 记录唯一标识号
    		var historyFileInfo = getLocalstorage(fileMd5);
    		if((!historyFileInfo || !equalsMap(historyFileInfo, webuploader_file_info) || file.size < webuploader_chunk_size)
    				|| !historyFileInfo["chunk"] || !historyFileInfo["chunks"] ){ // 判断是否存在附件历史上传信息
    			if(historyFileInfo['file_guid']){
    				$.post('/report/sys-manage/deleteTempFile',{
						'file_name': file.name,
						'file_guid': historyFileInfo['file_guid'],
						'busi_id': historyFileInfo['busi_id']
					},function(){
					},'json');
    			}
    			//file_guid = uploader.options.formData.file_guid;
    			webuploader_file_info["file_guid"] = file_guid;
    			webuploader_file_info["chunk"] = null;
    			setLocalstorage(fileMd5, webuploader_file_info); //存储附件信息
    			//progressbar.updateProgress(0, '<div style="margin: 10px auto auto auto">0%</div>');
    			deferred.resolve();
    		}else{
    			$.post('/report/sys-manage/checkTempFile',{
					'file_name': file.name,
					'file_guid': historyFileInfo['file_guid'],
					'busi_id': historyFileInfo['busi_id']
				},function(data){
					var historyChunk = data.file_size/webuploader_chunk_size - 1;
					webuploader_file_info["chunk"] = historyChunk;
					if(data.hasFile) {
						webuploader_file_info['file_guid'] = historyFileInfo['file_guid']; //存储附件信息
						var progress = parseInt(historyChunk)/parseInt(historyFileInfo["chunks"]); //计算历史上传进度
						progress = Math.floor(progress * 10000) / 100;
		    			progressbar.updateProgress(progress/100, '<div style="margin: 10px auto auto auto">' + progress + '%</div>');
		    			uploaderOpera.options.formData.file_guid = historyFileInfo['file_guid'];
						deferred.resolve(); //获取文件信息后进入下一步
					}else{
						$.post('/report/sys-manage/deleteTempFile',{
							'file_name': file.name,
							'file_guid': historyFileInfo['file_guid'],
							'busi_id': historyFileInfo['busi_id']
						},function(){
						},'json');
						webuploader_file_info['file_guid'] = file_guid; //存储附件信息
						setLocalstorage(fileMd5, webuploader_file_info);
						deferred.resolve(); //获取文件信息后进入下一步
					}
				},'json');
    		}
    	});
        return deferred.promise();
    },
    //时间点2：如果有分块上传，则每个分块上传之前调用此函数
    beforeSend:function(block){
        var deferred = WebUploader.Deferred();
        var historyFileInfo = getLocalstorage(fileMd5);
        //判断如果当前文件存在历史信息，且附件位置相同，则在之前的断点之前同意跳过
        if(historyFileInfo && equalsMap(historyFileInfo, webuploader_file_info) && historyFileInfo["chunk"]
        	&& block.chunk <= historyFileInfo["chunk"]){
        	deferred.reject();
        }else{
        	deferred.resolve();
        	webuploader_file_info['chunk'] = block.chunk; //获取当前上传的切片位置
        	webuploader_file_info['chunks'] = block.chunks; //记录切片数量
        	setLocalstorage(fileMd5, webuploader_file_info); //存储附件信息
        }
        return deferred.promise();
    },
    //时间点3：所有分块上传成功后调用此函数
    afterSendFile:function(){
    	deleteLocalstorage(fileMd5); //上传完成后在存储历史中删除附件信息
    }
});

/**
 * 获取当前时间
 * @returns
 */
function getWebuploaderDate(){
	return (new Date()).getTime();
}

/**
 * 添加按钮
 * @param createConfig
 * @returns {___anonymous38315_40578}
 */
function addUploadBtn(createConfig){
	return [
         {
             xtype: 'toolbar',
             dock: 'top',
             items: {
                 xtype: 'button',
                 text: '增行',
                 name: 'btn_add',
                 hidden: !createConfig.editable,
                 icon: '/report/image/sysbutton/add.png',
                 width: 70
             }
         }
     ]
	/*{
        xtype: 'toolbar',
        border: false,
        dock: 'top',
        items: [{
        	xtype: 'panel',
        	border:false,
        	layout:'hbox',
        	items:[{
        		  xtype: 'tbtext',
        		  cls: createConfig.gridConfig.itemId + '-btn',
        		  width: 90,
        		  height: 25,
        		  hidden: !createConfig.editable,
        		  text: '选择文件',
        		  listeners: {
        			  afterrender: function(self){
        				  if(IE8Del){
        					  $(self.el.dom).mouseenter(function(){
        						  onmouseleavedivIE();
        					  });                    					  
        				  }
        				  self.el.dom.style.backgroundColor='#00b7ee';
        				  self.el.dom.style.borderRadius = '3px';
        				  self.el.dom.style.height = '25px';
        				  self.el.dom.style.lineHeight = '5px';
        				  $(self.el.dom).on("click", function(btn){
        					  if(!is_install_flash){
        						  if(!Ext.ComponentQuery.query('window#ie-flash-tip-info')[0]){
        							  Ext.create('Ext.window.Window',{
             							 title: '提示信息',
             							 itemId: 'ie-flash-tip-info',
             							 width: 300,
             							 height: 140,
             							 buttonAlign: 'center',
             							 buttons: [
             							     {
             							    	 text: '确定',
             							    	 handler: function(btn){
             							    		 btn.up('window').close();
             							    	 }
             							     }
             							 ],
             							 items: [
             							    {
             							    	xtype: 'tbtext',
             							    	margin: '10 10 10 10',
             							    	html: '请先安装flash插件！点击此处下载' +
                                   				'<a href="javascript:void(0);" onclick=\'uploadFlashTool(\"install_flash_player_ax23.0.exe\")\'>flash插件</a></br>（安装成功后请重新登录系统再操作）'
             							    }
             							 ]
             						  }).show();
        						  }else{
        							  Ext.ComponentQuery.query('window#ie-flash-tip-info')[0].show();
        						  }
        					  }
        				  });
        			  }
        		  }
        	}]
        }]
	}*/
}

//表格的字段配置附件上传
function uploadFileCellItem(map){
    var busiId = map["busiId"];
    var busiType = map["busiType"];
    var busiProperty = map["busiProperty"];
    var editAble = map["editable"];
    if(!busiId){
        return null;
    }
    var editable = (typeof editAble!="undefined" && !editAble) ? editAble : true;
    //判断busiId是否存在
    $.get("/report/third-api/uploadFile/list", {
        busiId: busiId,
        busiType: busiType,
        busiProperty: busiProperty
    }, function(result) {
        var dt = $.parseJSON(result.data);
        var list = dt.list;
        var elements = document.getElementById("fileCell_"+busiId);
        if(list.length==0){ //不存在，上传
            if(editable){
                elements.innerHTML = '<div class="uploadpanel-btn uploadpanel-btn-upload" style="float: right;">' +
                    '<form id="fromCell_'+busiId+'" enctype="multipart/form-data">' +
                    ' <input type="file" name="file" onchange="cellUploadFile(this,\''+ busiId +'\',\''+ busiType +'\',\''+ busiProperty+'\',\''+ editable+'\')" ' +
                    ' style="filter:alpha(opacity:0);opacity:0;width:100%;cursor: pointer;font-size: 0;height: 100%;"/></form></div>';
            }
        } else { //存在：下载、删除
            var data = list[0];
            if(data.FILE_ID != null){ //已有附件
                var icon = '<image src="/report/image/file/docx.png">';
                const type_img = ['doc', 'docx', 'jpeg', 'jpg', 'pdf','png', 'ppt', 'pptx', 'rar', 'txt', 'xls', 'xlsx', 'zip'];
                var fileType = data.FILE_NAME.substring(data.FILE_NAME.lastIndexOf(".")+1);
                if(type_img.includes(fileType)){
                    icon = '<image src="/report/image/file/'+fileType+'.png">';
                }
                var deletebtn = !editable ? "" : '<div style="float: right;margin-left: 5px;" class="uploadpanel-btn uploadpanel-btn-delete" ' +
                    'onclick="deleteCellFile(\''+data.FILE_ID+'\',\''+data.FILE_NAME+'\',\''+busiId +'\',\''+ busiType +'\',\''+ busiProperty +'\',\''+ editable +'\')"></div>';
                elements.innerHTML = '<a style="color:#3329ff;display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' +
                    'cursor: pointer;'+(!editable?"width: 80%;":"width: 70%;")+'"' +
                    'onclick="downloadCellFile(\''+data.FILE_ID+'\')">' + icon + data.FILE_NAME +'</a>' +
                    deletebtn + '<div class="uploadpanel-btn uploadpanel-btn-download" style="float: right;margin-left: 5px;" onclick="downloadCellFile(\''+data.FILE_ID+'\')"></div>';
                //添加鼠标移入、移出事件
                $("#fileCell_"+busiId).mousemove(function(e) {
                    cellFileInfoShow(data.FILE_NAME,data.FILE_DESC,data.FILE_SIZE,data.UPLOAD_TIME);
                    var xx = e.originalEvent.x || e.originalEvent.layerX || 0;
                    var yy = (e.originalEvent.y || e.originalEvent.layerY || 0);
                    if(document.getElementById("fileCellInfoDiv")){
                        document.getElementById("fileCellInfoDiv").style.left = xx + 15;
                        document.getElementById("fileCellInfoDiv").style.top = yy + 18;
                        document.getElementById("fileCellInfoDiv").style.display = "block";
                    }
                });
                elements.parentElement.parentElement.setAttribute("onmouseout","cellFileInfoClose(\'"+busiId+"\')");
            } else{ //没有附件
                var updateBtn = !editable ? "" : ' <div class="uploadpanel-btn uploadpanel-btn-upload" style="float: right;">' +
                    ' <form id="fromCell_'+busiId+'" enctype="multipart/form-data">' +
                    ' <input type="file" name="file" onchange="cellUploadFile(this,\''+ busiId +'\',\''+ busiType +'\',\''+ busiProperty +'\',\''+ editable +'\',\''+ data.RULE_ID
                    +'\',\''+ data.IS_LIMITTYPE+'\',\''+ data.FILE_SUFFIX+'\',\''+ data.IS_LIMITSIZE +'\',\''+ data.MAXLIMIT +'\',\''+ data.MINLIMIT  +'\')" ' +
                    ' style="filter:alpha(opacity:0);opacity:0;width:100%;cursor: pointer;font-size: 0;height: 100%;"/></form></div>';
                elements.innerHTML = (data.FILE_DESC!=null ? "<div style='display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width: 80%'>"+data.FILE_DESC+"</div>" : '') + updateBtn;
            }
        }
    }, "json");
    return "<div id='fileCell_"+busiId+"'></div>";
}

//表格的单元格文件上传
function cellUploadFile(self, busiId, busiType, busiProperty, editable , ruleId, isLimitType, fileSuffix, isLimitSize, maxLimit, minLimit) {
    //创建进度条
    Ext.MessageBox.show({
        msg: '正在上传附件,请耐心等待...',
        progressText: '正在上传...',
        width: 300,
        wait: {
            interval: 300
        },
        animateTarget: self
    });
    //获取校验文件类型
    var file_suffix = (!!getSysParam('DEBT_FILE_TYPE') ? getSysParam('DEBT_FILE_TYPE') : ".doc/.docx/.pdf/.jpg/.jpeg/.png");//文件类型限制
    if (typeof isLimitType != 'undefined' && isLimitType != null && isLimitType != 0) {
        file_suffix = fileSuffix;//从附件规则获取文件类型限制
    }
    if (file_suffix != null && file_suffix != '') {
        //获取上传文件的后缀名
        var filePath = $(self).val();
        var fileExt = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        //上传文件与数据库中的文件格式比较
        var flag = file_suffix.toLowerCase().indexOf(fileExt);
        if (flag == null || flag < 0) {
            Ext.Msg.alert('提示', '文件类型错误,请选择文件' + file_suffix);
            return false;
        }
    }
    //获取校验文件大小
    var maxlimit = (!!getSysParam('DEBT_FILE_SIZE') ? getSysParam('DEBT_FILE_SIZE') : 1024 * 1024);//文件大小最大值
    var minlimit = 0; //文件大小最小值
    if (typeof isLimitSize != 'undefined' && isLimitSize != null && isLimitSize != 0) {
        maxlimit = maxLimit;//从附件规则获取文件大小限制
        minlimit = minLimit;
    }
    if (maxlimit != null && maxlimit != '') {
        var fileSize = getFileSize(self);
        if (fileSize > maxlimit) {
            Ext.Msg.alert('提示', '文件太大，请选择小于' + maxlimit + 'KB的文件！');
            return false;
        }
        if (fileSize < minlimit) {
            Ext.Msg.alert('提示', '文件太小，请选择大于' + minlimit + 'KB的文件！');
            return false;
        }
    }
    // 上传附件
    $('form#fromCell_'+busiId).ajaxSubmit({
        url: '/report/third-api/uploadFile/file',
        type: 'POST',
        dataType: 'json',
        data: {
            busiId: busiId,
            busiType: busiType,
            busiProperty: busiProperty,
            ruleId: ruleId
        },
        resetForm: true,
        clearForm: true,
        success: function (result) {
            Ext.MessageBox.hide();
            if(result.code==20000){
                var data =JSON.parse(result.data);
                if(data.success){
                    //提示上传成功
                    Ext.toast({
                        html: '<div style="text-align: center;">上传成功!</div>',
                        closable: false,
                        align: 't',
                        slideInDuration: 400,
                        minWidth: 400
                    });
                    //刷新单元格
                    uploadFileCellItem ({
                        busiId: busiId,
                        busiType: busiType,
                        busiProperty: busiProperty,
                        editable: editable
                    });
                } else {
                    Ext.Msg.alert('提示', "上传失败！");
                }
            }else{
                Ext.Msg.alert('提示', "上传失败！");
            }
        }
    });
}

/**
 * 计算文件大小，返回文件大小值，单位K
 * @param target
 * @returns {number}
 */
function getFileSize(target) {
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    var fs = 0;
    if (isIE && !target.files) {//如果是ie浏览器，使用ActiveXObject控件判断大小，不支持IE8
        var filePath = target.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile(filePath);
        fs = file.Size;
    } else if (target.files && target.files.length > 0) {//非IE浏览器判断大小
        fs = target.files[0].size;
    } else {
        fs = 0;
    }
    if (fs > 0) {
        fs = fs / 1024;
    }
    return fs;
}

//表格的单元格文件删除
function deleteCellFile(fileId, fileName, busiId, busiType, busiProperty, editable){
    Ext.Msg.confirm('提示', '是否删除附件 ' + fileName, function (btn) {
        if (btn == 'yes') {
            //发送请求:删除当前附件
            $.ajax({
                url: '/report/third-api/uploadFile/deleteFileSingle',
                type: 'DELETE',
                data: {fileId : fileId},
                success: function (res) {
                    if (res.code == 20000) {
                        //提示上传成功
                        Ext.toast({
                            html: '<div style="text-align: center;">删除成功!</div>',
                            closable: false,
                            align: 't',
                            slideInDuration: 400,
                            minWidth: 400
                        });
                        //刷新单元格
                        var elements = document.getElementById("fileCell_"+busiId);
                        $("#fileCell_"+busiId).unbind("mousemove");
                        elements.parentElement.parentElement.removeAttribute("onmouseout");
                        document.getElementById("fileCellInfoDiv").remove();
                        uploadFileCellItem ({
                            busiId: busiId,
                            busiType: busiType,
                            busiProperty: busiProperty,
                            editable: editable
                        });
                    } else {
                        Ext.Msg.alert('提示', res.msg);
                    }
                }
            });
        }
    });
}

//表格的单元格文件下载
function downloadCellFile(fileId){
    // window.location.href = '/report/third-api/downloadFile?fileId=' + fileId;
    downloadPublicFiles('/report/third-api/downloadFile', "GET", {
        fileId:fileId
    })
}

//显示单元附件信息
function cellFileInfoShow(fileName, fileDesc, fileSize, time){
    //鼠标移上去的附件信息
    if(!document.getElementById("fileCellInfoDiv")) {
        var infoDiv = document.createElement("div");
        infoDiv.setAttribute("id", "fileCellInfoDiv");
        infoDiv.setAttribute("class", "x-tip x-layer x-tip-default x-border-box")
        infoDiv.setAttribute("style", "z-index: 19001;background-color: rgb(255, 255, 204);display: none;");
        top.document.body.append(infoDiv);
        var infoSpan1 = document.createElement("span");
        infoSpan1.setAttribute("id","cellFileName");
        var infoSpan2 = document.createElement("span");
        infoSpan2.setAttribute("id","cellFileDesc");
        var infoSpan3 = document.createElement("span");
        infoSpan3.setAttribute("id","cellFileSize");
        var infoSpan4 = document.createElement("span");
        infoSpan4.setAttribute("id","cellFileUploadTime");
        infoDiv.append(infoSpan1);
        infoDiv.append(infoSpan2);
        infoDiv.append(infoSpan3);
        infoDiv.append(infoSpan4);
    }
    if(!!document.getElementById("fileCellInfoDiv")){
        //隐藏原有的tip
        if(document.getElementsByClassName("x-layer x-tip-default x-border-box")){
            var doc = document.getElementsByClassName("x-layer x-tip-default x-border-box");
            for(var i=0; i< doc.length; i++){
                document.getElementsByClassName("x-layer x-tip-default x-border-box").item(i).style.display = "none";
            }
            if(document.getElementsByClassName("x-css-shadow").item(0)){
                document.getElementsByClassName("x-css-shadow").item(0).style.display = "none";
            }
        }
        //显示添加的tip
        document.getElementById("cellFileName").innerHTML = "文件名称：" + fileName +"<br />";
        if(fileDesc!=null && fileDesc!="null"){
            document.getElementById("cellFileDesc").innerHTML = "文件说明：" + fileDesc +"<br />";
        }
        document.getElementById("cellFileSize").innerHTML = "文件大小：" + fileSize +"<br />";
        document.getElementById("cellFileUploadTime").innerHTML = "上传时间：" + time;
    }
}

//隐藏单元附件信息
function cellFileInfoClose(){
    if(document.getElementById("fileCellInfoDiv")){
        document.getElementById("fileCellInfoDiv").style.display = "none";
    }
}
